/**
 * ********************************************************
 * <p>
 * Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved
 * <p>
 * ********************************************************
 *
 * @date: 2018/11/5
 * @author: licong08
 * @description: Blank
 */
package com.baidu.mpks.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class CleanUtil {
    public static int TYPE_PATTERN = 1;
    public static int TYPE_REPLACE = 2;
    private List<Cleaner> cleaners;

    public CleanUtil() {
        cleaners = new ArrayList<>();
    }

    public CleanUtil addStrCleaner(String matcher, String replacement) {
        cleaners.add(new StrCleaner(matcher, replacement));
        return this;
    }

    public CleanUtil addPatternCleaner(String matcher, String replacement) {
        cleaners.add(new PatternCleaner(matcher, replacement));
        return this;
    }

    public String clean(String str) {
        for (Cleaner cleaner : cleaners) {
            str = cleaner.clean(str);
        }
        return str;
    }

    private interface Cleaner {
        String clean(String str);
    }

    private class StrCleaner implements Cleaner {
        private String strMatcher;
        private String replacement;

        StrCleaner(String matcher, String replacement) {
            this.strMatcher = matcher;
            this.replacement = replacement;
        }

        public String clean(String content) {
            return content.replace(strMatcher, replacement);
        }
    }

    private class PatternCleaner implements Cleaner {
        private Pattern regexMatcher;
        private String replacement;

        PatternCleaner(String matcher, String replacement) {
            this.regexMatcher = Pattern.compile(matcher);
            this.replacement = replacement;
        }

        public String clean(String content) {
            return regexMatcher.matcher(content).replaceAll(replacement);
        }
    }
}
